package com.wantupai.translate.activity.camear;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;
import com.wantupai.translate.R;
import com.wantupai.translate.activity.CardActivity;
import com.wantupai.translate.activity.PersonalInfoActivity;
import com.wantupai.translate.activity.PicActivity;
import com.wantupai.translate.adapter.NcTabAdapter;
import com.wantupai.translate.base.BaseActivity;
import com.wantupai.translate.bean.MenuBean;
import com.wantupai.translate.utils.MyLog;
import com.wantupai.translate.utils.SspImageUtils;
import com.wantupai.translate.utils.ToastUtils;
import com.wantupai.translate.widget.AutoLocateHorizontalView;
import com.wantupai.translate.widget.SspCameraPreview;
import com.wantupai.translate.widget.SspGridlineView;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class CameraActivity extends BaseActivity {

    @BindView(R.id.nc_camera)
    SspCameraPreview ncCamera;
    @BindView(R.id.head)
    ImageView head;
    @BindView(R.id.nc_flash)
    ImageView ncFlash;
    @BindView(R.id.ssp_camera_top)
    RelativeLayout sspCameraTop;
    @BindView(R.id.aperture)
    ImageView aperture;
    @BindView(R.id.hint)
    TextView hint;
    @BindView(R.id.type)
    ImageView typeImg;
    @BindView(R.id.type_text)
    TextView typeText;
    @BindView(R.id.z_base_camera_over_img)
    RelativeLayout mLayer;
    @BindView(R.id.ssp_camera_scan)
    ImageView sspCameraScan;
    @BindView(R.id.nc_countdown)
    TextView ncCountdown;
    @BindView(R.id.ssp_camera_autoscreen)
    RelativeLayout sspCameraAutoscreen;
    @BindView(R.id.nc_line)
    SspGridlineView ncLine;
    @BindView(R.id.nc_seek)
    SeekBar ncSeek;
    @BindView(R.id.nc_tab)
    AutoLocateHorizontalView ncTab;
    @BindView(R.id.nc_dcim)
    ImageView ncDcim;
    @BindView(R.id.ssp_camera_bottom)
    LinearLayout sspCameraBottom;
    @BindView(R.id.ssp_camera_img)
    ImageView sspCameraImg;
    @BindView(R.id.ssp_camera_anim)
    ImageView sspCameraAnim;
    @BindView(R.id.ssp_camera_anim_s)
    ImageView sspCameraAnimS;
    @BindView(R.id.ssp_camera_anim_ss)
    ImageView sspCameraAnimSs;
    @BindView(R.id.ssp_camera_timer)
    TextView sspCameraTimer;
    @BindView(R.id.btn_take_translate)
    TextView btnTakeTranslate;
    @BindView(R.id.btn_take_word)
    TextView btnTakeWord;
    @BindView(R.id.btn_take_card)
    TextView btnTakeCard;
    private Vibrator vibrator;
    private ImagePicker imagePicker;
    private ScaleAnimation scaleAnimation1, scaleAnimation2, scaleAnimation3, scaleAnimation4, scaleAnimation5, scaleAnimation6;
    private String code = "takeword";
    private int index = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_newcamera;
    }

    @Override
    public void initViews() {
        imagePicker = new ImagePicker();
        imagePicker.setTitle("选择图像");
        imagePicker.setCropImage(true);
//        缩放
        scaleAnimation1 = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation2 = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation3 = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation4 = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation5 = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation6 = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    }

    @Override
    protected boolean translucentStatusBar() {
        return true;
    }

    @Override
    public void initListener() {
    }

    @Override
    public void initData() {
        ncCamera.init(Camera.CameraInfo.CAMERA_FACING_BACK);
        initTab();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (vibrator == null)
            return;
        vibrator.cancel();
    }

    @Override
    public void processClick(View v) {
    }

    private boolean isOpen;

    private void light() {
        if (!isOpen) {
            if (ncCamera.openLight()) {
                isOpen = true;
                ncFlash.setImageResource(R.mipmap.ic_flash2);
            }
        } else {
            if (ncCamera.closeLight()) {
                isOpen = false;
                ncFlash.setImageResource(R.mipmap.ic_flash);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLayer.clearAnimation();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void takePic(final String code) {
        try {
            ncCamera.takePicture(new SspCameraPreview.OnPictureTakenListener() {
                @Override
                public void onSuccess(final Bitmap bitmap) {
                    sspCameraImg.post(new Runnable() {
                        @Override
                        public void run() {
                            if ("translate".equals(code)) {
                                File file = SspImageUtils.saveBmp(getBaseContext(), bitmap, String.valueOf(System.currentTimeMillis()));
                                startActivity(new Intent(CameraActivity.this, PicActivity.class).putExtra("Translate",true).putExtra("picPath", file.getAbsoluteFile().toString()));
                            } else if ("takeword".equals(code)) {
                                File file = SspImageUtils.saveBmp(getBaseContext(), bitmap, String.valueOf(System.currentTimeMillis()));
                                startActivity(new Intent(CameraActivity.this, PicActivity.class).putExtra("picPath", file.getAbsoluteFile().toString()));
                            } else {
                                Matrix matrix = new Matrix();
                                // 设置旋转角度
                                matrix.setRotate(-90);
                                // 重新绘制Bitmap
                                Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                                File file = SspImageUtils.saveBmp(getBaseContext(), bitmap1, String.valueOf(System.currentTimeMillis()));
                                startActivity(new Intent(CameraActivity.this, CardActivity.class).putExtra("picPath", file.getAbsoluteFile().toString()));
                            }
                        }
                    });
                }

                @Override
                public void onFailed(String msg) {
                    ToastUtils.show(msg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initTab() {
        final int type = getIntent().getIntExtra("type", 0);
//        if (SousouApi.getTypeList() == null) return;
//        for (int i = 0; i < SousouApi.getTypeList().size(); i++) {
//            if (SousouApi.getTypeList().get(i).getType() == type) {
//                index = i;
//            }
//        }
        ArrayList<MenuBean> typeList = new ArrayList<>();
        for (int i = 0; i <3 ; i++) {
            MenuBean bean = new MenuBean();
            bean.setType(i);
            if (i == 0){
                bean.setSimple_name("取字");
            }else if (i==1){
                bean.setSimple_name("翻译");
            }else{
                bean.setSimple_name("名片拍摄");
            }
            typeList.add(bean);
        }

        final NcTabAdapter ageAdapter = new NcTabAdapter(this, typeList, index);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        ncTab.setLayoutManager(linearLayoutManager);
        ncTab.setOnSelectedPositionChangedListener(new AutoLocateHorizontalView.OnSelectedPositionChangedListener() {
            @Override
            public void selectedPositionChanged(int pos) {
                vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                long[] pattern = {5, 30}; // 停止 开启 停止 开启
                vibrator.vibrate(pattern, -1); //重复两次上面的pattern 如果只想震动一次，index设为-1
                index = pos;

                switch (pos){
                    case 0:
                        code = "takeword";
                        mLayer.setVisibility(View.GONE);
                        break;
                    case 1:
                        code = "translate";
                        mLayer.setVisibility(View.GONE);
                        break;
                    case 2:
                        code = "takecard";
                        mLayer.setVisibility(View.VISIBLE);
                        break;
                }
            }

        });
        ncTab.setInitPos(index);
        ncTab.setAdapter(ageAdapter);
        ageAdapter.notifyDataSetChanged();
    }

    public void selectPos(int pos) {
        ncTab.moveToPosition(pos);
    }


    @OnClick({R.id.nc_take, R.id.ar, R.id.head, R.id.nc_dcim, R.id.btn_take_card, R.id.nc_flash, R.id.btn_take_translate, R.id.btn_take_word})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.nc_take:
                takePic(code);
                break;
            case R.id.ar:
                break;
            case R.id.head:
                startActivity(new Intent(CameraActivity.this, PersonalInfoActivity.class));
                break;
            case R.id.nc_dcim:
                sspCameraScan.clearAnimation();
                sspCameraScan.setVisibility(View.GONE);
                imagePicker.startGallery(this, new ImagePicker.Callback() {
                    @Override
                    public void onPickImage(Uri imageUri) {
                    }

                    @Override
                    public void onCropImage(final Uri imageUri) {// 裁剪图片回调
                        try {
                            File file = new File(new URI(imageUri.toString()));
                            MyLog.e("sss", file.getAbsoluteFile().toString());

                            if ("translate".equals(code)) {
                                startActivity(new Intent(CameraActivity.this, PicActivity.class).putExtra("picPath", file.getAbsoluteFile().toString()));
                            } else if ("takeword".equals(code)) {
                                startActivity(new Intent(CameraActivity.this, PicActivity.class).putExtra("picPath", file.getAbsoluteFile().toString()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void cropConfig(CropImage.ActivityBuilder builder) { // 自定义裁剪配置
                    }

                    @Override
                    public void onPermissionDenied(int requestCode, String[] permissions,
                                                   int[] grantResults) { // 用户拒绝授权回调
                    }
                });
                break;
            case R.id.nc_flash:
                light();
                break;
            case R.id.btn_take_card:
                code = "takecard";
                mLayer.setVisibility(View.VISIBLE);
                btnTakeCard.setTextColor(ContextCompat.getColor(this, R.color.title_face));
                btnTakeTranslate.setTextColor(ContextCompat.getColor(this, R.color.white));
                btnTakeWord.setTextColor(ContextCompat.getColor(this, R.color.white));
                break;
            case R.id.btn_take_translate:
                mLayer.setVisibility(View.GONE);
                code = "translate";
                btnTakeTranslate.setTextColor(ContextCompat.getColor(this, R.color.title_face));
                btnTakeWord.setTextColor(ContextCompat.getColor(this, R.color.white));
                btnTakeCard.setTextColor(ContextCompat.getColor(this, R.color.white));
                break;
            case R.id.btn_take_word:
                mLayer.setVisibility(View.GONE);
                code = "takeword";
                btnTakeCard.setTextColor(ContextCompat.getColor(this, R.color.white));
                btnTakeTranslate.setTextColor(ContextCompat.getColor(this, R.color.white));
                btnTakeWord.setTextColor(ContextCompat.getColor(this, R.color.title_face));
                break;
            default:
                break;
        }
    }
}
